const YZAPI = require('./apis/youzanyun-api');
const assert = require('assert');

class SecretClient {
    constructor(getTokenFnAsync) {
        assert(typeof getTokenFnAsync === 'function', '非正确的回调函数getTokenFnAsync');
        this.getTokenFnAsync = getTokenFnAsync;
    }

    /**
     * 加密
     * @param {*} source
     */
    async encrypt(source) {
        if (typeof source == 'string') {
            let token = await this.getTokenFnAsync();
            let ciphertext = await YZAPI.singleEncrypt(token, source);
            return ciphertext;
        } else if (source instanceof Array) {
            let token = await this.getTokenFnAsync();
            let res = await YZAPI.batchEncrypt(token, source);
            return res;
        }
        console.error('错误的source类型', source);
        throw new Error('错误的source类型');
    }

    /**
     * 解密
     * @param {*} yzToken
     * @param {*} source
     */
    async decrypt(source) {
        if (typeof source == 'string') {
            let token = await this.getTokenFnAsync();
            let plaintext = await YZAPI.singleDecrypt(token, source);
            return plaintext;
        } else if (source instanceof Array) {
            let token = await this.getTokenFnAsync();
            let res = await YZAPI.batchDecrypt(token, source);
            return res;
        }
        console.error('错误的source类型', source);
        throw new Error('错误的source类型');
    }

    /**
     * 判断是否为密文
     * @param {*} data
     */
    async isEncrypt(data) {
        if (typeof data == 'string') {
            let token = await this.getTokenFnAsync();
            return await YZAPI.singleQueryEncryptStatus(token, data);
        } else if (data instanceof Array) {
            let token = await this.getTokenFnAsync();
            return await YZAPI.batchQueryEncryptStatus(token, data);
        }
        console.error('错误的数据类型', data);
        throw new Error('错误的数据类型');
    }
}

module.exports = SecretClient;
